package com.lie.prepare.merge;

import org.junit.Test;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Random;

import static com.lie.prepare.sort.util.MyArrayHelper.*;
import static com.lie.prepare.util.Print.*;

/**
 * Created by lie on 2018/4/20.
 * 两条有序链表的合并
 * 但这里引用了LinkedList
 * 我想做一个更纯粹的合并
 * 于是我做了另外的练习
 * @see NodeMerge
 *
 */
public class LinkMerge {

    private static LinkedList<Integer> link1 = generateLink1();
    private static LinkedList<Integer> link2 = generateLink2();

    private static LinkedList<Integer> generateLink1(){
        LinkedList<Integer> linkedList = new LinkedList<Integer>();
        linkedList.add(1);
        linkedList.add(3);
        linkedList.add(5);
        linkedList.add(6);
        linkedList.add(10);
        return linkedList;
    }
    private static LinkedList<Integer> generateLink2(){
        LinkedList<Integer> linkedList = new LinkedList<Integer>();
        linkedList.add(2);
        linkedList.add(4);
        linkedList.add(4);
        linkedList.add(8);
        linkedList.add(9);
        return linkedList;
    }

    @Test
    public void testLink(){
        print(Arrays.toString(link1.toArray()));
        print(Arrays.toString(link2.toArray()));
    }

    @Test
    public void testAddAll(){
        link1.addAll(3, link2);
        print(Arrays.toString(link1.toArray()));
    }

    @Test
    public void merge(){
        int size1 = link1.size();
        int size2 = link2.size();

        int indexLeft = 0;
        int indexRight = 0 ;

        LinkedList<Integer> temp = new LinkedList<Integer>();

        while (indexLeft < size1 && indexRight < size2) {
            if (link1.get(indexLeft) < link2.get(indexRight)) {
                temp.add(link1.get(indexLeft++));
            }else {
                temp.add(link2.get(indexRight++));
            }
        }

        while (indexLeft < size1) {
            temp.add(link1.get(indexLeft++));
        }
        while (indexRight < size2) {
            temp.add(link2.get(indexRight++));
        }

        print(Arrays.toString(temp.toArray()));

    }
}
